package com.example.sourcecodelearning.modules.operationlog.service;

import com.example.framework.common.event.OperationLogEvent;
import com.example.framework.mq.kafka.core.service.KafkaConsumerService;
import com.example.sourcecodelearning.modules.operationlog.dataobject.OperationLogDO;
import com.example.sourcecodelearning.modules.operationlog.mapper.OperationLogMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class OperationLogService extends KafkaConsumerService<OperationLogEvent> {

    @Resource
    private OperationLogMapper operationLogMapper;

    @Override
    public void consume(String topic, OperationLogEvent operationLogEvent) {
        log.info("OperationLogService收到消息，msgBody={}", operationLogEvent);
        // 有可能直接发送了操作日志的mq topic，由于body不是从切面封装的对象，导致这里的值都是空的，忽略这种数据（切面发送的消息一定有applicationName）
        if (operationLogEvent == null || operationLogEvent.getApplicationName() == null) {
            return;
        }
        operationLogMapper.insert(OperationLogDO.builder()
                .userId(operationLogEvent.getUserId())
                .operation(operationLogEvent.getOperation())
                .traceId(operationLogEvent.getTraceId())
                .applicationName(operationLogEvent.getApplicationName())
                .path(operationLogEvent.getPath())
                .method(operationLogEvent.getMethod())
                .params(operationLogEvent.getParams())
                .costTime(operationLogEvent.getCostTime())
                .ip(operationLogEvent.getIp())
                .retCode(operationLogEvent.getRetCode())
                .result(operationLogEvent.getResult())
                .build());
    }
}
